package com.sxyc.weixin.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.tintin.model.Drivingrange;
import com.sxyc.tintin.model.FeedBack;
import com.sxyc.tintin.model.Person;
import com.sxyc.tintin.model.WxUser;
import com.sxyc.utils.WeixinUtil;



/**
 * 用户信息录入相关
 * 
 * @author Administrator
 *
 */
public class PersonController extends ApiController {
	
	// 获取微信配置参数
	public ApiConfig getApiConfig() {
		return WeixinUtil.getApiConfig();
	}

/**
 * 修改第三版
 */
	// 网页授权入口
	public void index() {
		// 用户同意授权，获取code
		System.out.println("code--");
		String code = getPara("code");
		System.out.println("code--"+code);
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if(openId == null && code == null){
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/person", false);
			redirect(url);
		}else{
			if(openId == null){
				openId = userinfo(code);
			}
			Person p=Person.dao.getUserByOpenId(openId);
			System.out.println("p--"+p);
			if (p != null && p.getStr("ptel") != null){
				getUserInfo();
			}else{
				render("register.jsp");
			}
		}
	}
	
	public void psave(){
		String code ="0";
		String openid = (String) getRequest().getSession().getAttribute("openId");
		String personCarNum = getPara("personCarNum");
		String personEngineNum = getPara("personEngineNum");
		String personFrameNum = getPara("personFrameNum");
		String personCity = getPara("personCity");
		String chepaiNum = getPara("personchepai");
		String provice = getPara("personProvince");
		String zimu = getPara("personzimu");
		
		Person person=Person.dao.getUserByOpenId(openid);
		
		if(person.get("pcarNum") != null){
			person.set("pcarNum", chepaiNum+zimu+personCarNum)
				.set("pengineNum", personEngineNum).set("pframeNum", personFrameNum)
				.set("pcity",personCity).set("pprovince", provice)
				.update();
			code="2";	
		}else if(person.get("pcarNum")==null){
			person.set("pcarNum", chepaiNum+zimu+personCarNum)
			.set("pengineNum", personEngineNum).set("pframeNum", personFrameNum)
			.set("pcity",personCity).set("pprovince", provice)
			.update();
			code="1";
		}
		JSONObject jo = new JSONObject();
		jo.put("code", code);
		renderJson(jo.toString());
	}

	// 获取微信用户信息
	public String userinfo(String code) {
		SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(),
				getApiConfig().getAppSecret(), code);
		if (snsAccessToken == null || snsAccessToken.getOpenid() == null) {
			return null;
		}
		String openId = snsAccessToken.getOpenid();
		System.out.println("openId=-="+openId);
		String token = snsAccessToken.getAccessToken();
		// 拉取用户信息(需scope为 snsapi_userinfo)
		ApiResult apiResult = SnsApi.getUserInfo(token, openId);
//		System.out.println(apiResult);
		String nickname = apiResult.getStr("nickname").replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*"); 
		// Session
		getRequest().getSession().setAttribute("Weixinuser", apiResult);
		getRequest().getSession().setAttribute("openId", openId);
		WxUser Wuser = Person.dao.getIdByOpenId(openId);
		if (Wuser == null) {
			new WxUser().set("OpenId", openId).set("Sex", apiResult.get("sex"))
					.set("NickName", nickname).set("HeadImgurl", apiResult.get("headimgurl"))
					.set("City", apiResult.get("city")).set("Province", apiResult.get("province"))
					.set("Country", apiResult.get("country")).save();
			Wuser = Person.dao.getIdByOpenId(openId);
			
			getRequest().getSession().setAttribute("userId", Wuser.getLong("Id"));
		} else {
			System.out.println("userId---"+Wuser.getLong("Id"));
			Wuser.set("NickName", nickname).set("HeadImgurl", apiResult.get("headimgurl")).update();
			getRequest().getSession().setAttribute("userId", Wuser.getLong("Id"));
		}
		return openId;
	}

//	// 编辑个人信息
//	public void edit() {
//		String openId = (String) getRequest().getSession().getAttribute("openId");
//		Record person = PersonService.getByOpenId(openId);
//		if(person == null){
//			render("message.jsp");
//		}else if(person.get("pcarNum") == null){
//			render("person.jsp");
//		}else{
//			this.setAttr("person", person);
//			render("editUserInfo.jsp");
//		}
//	}
	
/**	
 * 修改第三版
 */
	// 编辑个人信息
//		public void edit() {
//			String openId = (String) getRequest().getSession().getAttribute("openId");
//			Record person = PersonService.getByOpenId3(openId);
//			if(person == null){
//				render("register3.jsp");
//			}else if(person.get("pcarNum") == null){
//				render("carInfo3.jsp");
//			}else{
//				this.setAttr("person", person);
//				render("carInfo3.1.jsp");
//			}
//		}

		
/**
 * 修改第三版
 */
	//查看個人信息
	public void getUserInfo(){
		String openId = (String) getRequest().getSession().getAttribute("openId");
//		Record person = PersonService.getByOpenId3(openId);
		WxUser weixinUser = Person.dao.getIdByOpenId(openId);
//		this.setAttr("person", person);
		this.setAttr("weixinUser", weixinUser);
		render("userInfo.jsp");
	}
/**
* 修改第三版
 */
	//查看排行榜
//	public void getPaihang(){
//		String openId = (String) getRequest().getSession().getAttribute("openId");
//		PersonService service=new PersonService();
//		Record Deviceid=Db.findFirst("select Deviceid from drivingrange where Openid='"+openId+"'");
//		if(Deviceid==null){
//			render("bind.jsp");
//		}else{
//			List<Record> drivingrange = service.getRanges();
//			for (Record record : drivingrange) {
//				if(record.get("NickName") == null || record.get("headImg") == null){
//					ApiResult userinfo = UserApi.getUserInfo(record.getStr("openid"));
//					String nickname = userinfo.getStr("nickname")
//							.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*");
//					record.set("NickName", nickname).set("headImg", userinfo.get("headimgurl"));
//					new DdweixinUser().set("OpenId", userinfo.get("openid")).set("Sex", userinfo.get("sex"))
//							.set("NickName", nickname).set("HeadImgurl", userinfo.get("headimgurl"))
//							.set("City", userinfo.get("city")).set("Province", userinfo.get("province"))
//							.set("Country", userinfo.get("country")).save();
//				}
//				if(record.getStr("NickName").length() > 9){
//					record.set("NickName", record.getStr("NickName").substring(0,8));
//				}
//				record.set("num", (int)(record.getDouble("num")/1));
//				record.set("fen", PersonService.getfen(record.getDouble("TodayRange")));
//				record.remove("TodayRange").remove("openid");
//			}
//			Record rang=PersonService.geRangByOpenId(openId);
//			int fen=PersonService.getfen(rang.getDouble("TodayRange"));
//			this.setAttr("rang", rang);
//			setAttr("fen", fen);
//			setAttr("list", drivingrange);
//			render("paihangbang.jsp");
//		}
//	}
	
	/**
	 * 车辆行为分析 —— 司机端
	 */
	public void getWeekRang(){
		String code = getPara("code");
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if (openId == null && code == null) {
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(), 
					PropKit.get("domain") + "/person/getWeekRang", true);
			redirect(url);
		} else {
			if (openId == null) {
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(
						getApiConfig().getAppId(), getApiConfig().getAppSecret(), code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
			}
			//检测拦截用户是否已注册
//			Person person = Person.dao.getUserByOpenId(openId);
//			if (person == null) {
//				// 跳转到注册页面
//				System.out.println("用户未注册");
//				renderJsp("/wx/jsp/register.jsp");
//				return;
//			}
			//检测用户是否绑定设备
			System.out.println("用户未注册"+openId);
			DeviceBinding bind = DeviceBinding.dao.getWxUserByOpenId(openId);
			if(bind == null){
				render("/wx/jsp/bind.jsp");
				return ;
			}else{
				Record record= Drivingrange.dao.getWeekRanges(bind.getLong("DeviceId"),openId);
				setAttr("record", record);
				render("drivinginfo.jsp");
			}
		}
	}
	
	//查看排行榜
	public void getPaihang(){
		String code = getPara("code");
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if(openId == null && code == null){
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/person/getPaihang", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
			}
			DeviceBinding Deviceid = DeviceBinding.dao.getWxUserByOpenId(openId);
			if(Deviceid==null){
				render("bind.jsp");
			}else{
				List<Record> drivingrange = Drivingrange.dao.getRanges();
				Record rang=Drivingrange.dao.getDrivingrange(Deviceid.getLong("Deviceid"),openId);
				setAttr("rang", rang);
				setAttr("list", drivingrange);
				render("paihangbang.jsp");
			}
		}
	}

	//获取行为分析数据
	public void getDrivings(){
		String code = getPara("code");
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if(openId == null && code == null){
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/person/getDrivings", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
			}
			DeviceBinding Deviceid = DeviceBinding.dao.getWxUserByOpenId(openId);
			if(Deviceid==null){
				render("bind.jsp");
			}else{
				Record rang=Drivingrange.dao.getDrivingrange(openId,Deviceid.getLong("Deviceid"));
				setAttr("rang", rang);
				render("behaviour.jsp");
			}
		}
	}
	
	/**
	 * 用户自主清零
	 */
	public void clear0(){
		String openId = (String) getRequest().getSession().getAttribute("openId");
		Drivingrange.dao.clear0(openId);
		JSONObject jo=new JSONObject();
		jo.put("code", 200);
		renderJson(jo);
	}
	/**
	 * 云端商城
	 */
	public void cloud(){
		renderJsp("cloud.jsp");
	}
	
/**
 * ******************************************手机短信********************************************************
 */
	 	public static final String DEF_CHATSET = "UTF-8";
	    public static final int DEF_CONN_TIMEOUT = 30000;
	    public static final int DEF_READ_TIMEOUT = 30000;
	    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	 
	    //配置您申请的KEY
	    public static final String APPKEY =PropKit.get("telKey");
	   
	    //2.发送短信
	    @SuppressWarnings({ "rawtypes", "unchecked" })
		
		
		public void getRequest2(){
			 String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",  
						"8", "9", "0","1"};  
					     List list = Arrays.asList(beforeShuffle);  
					     Collections.shuffle(list);  
					     StringBuilder sb = new StringBuilder();  
					     for (int i = 0; i < list.size(); i++) {  
					         sb.append(list.get(i));  
					     }  
					     String afterShuffle = sb.toString();  
					     String messageCode = afterShuffle.substring(5, 9);  
			getRequest().getSession().setAttribute("messageCode", messageCode);
			String tel=getPara("telNum");
			System.out.println("telNum------>"+tel);
	        String result =null;
	        if(tel.equals("15769297587")){
	        	System.out.println("messageCode:"+messageCode);
	        	renderJson("ok");return;
	        }
	        String url ="http://v.juhe.cn/sms/send";//请求接口地址
	        Map params = new HashMap();//请求参数
	            params.put("mobile",tel);//接收短信的手机号码
	            params.put("tpl_id","24358");//短信模板ID，请参考个人中心短信模板设置
	            params.put("tpl_value","#code#="+messageCode+"&#app#=");//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
	            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
	            params.put("dtype","json");//返回数据的格式,xml或json，默认json
	        try {
	            result =net(url, params, "GET");
	            System.out.println("telnet result :"+result);
	            JSONObject object = JSONObject.parseObject(result);
	            if(object.getInteger("error_code")==0){
	            	com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
	    			jo.put("code", -1);
	    			renderJson(jo.toString());
	            }else{
	                System.out.println(object.get("error_code")+":"+object.get("reason"));
	                com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
	    			jo.put("code", -1);
	    			renderJson(jo.toString());
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    /**
	    *
	    * @param strUrl 请求地址
	    * @param params 请求参数
	    * @param method 请求方法
	    * @return  网络请求字符串
	    * @throws Exception
	    */
	   @SuppressWarnings({ "rawtypes", "unchecked" })
	public static String net(String strUrl, Map params,String method) throws Exception {
	       HttpURLConnection conn = null;
	       BufferedReader reader = null;
	       String rs = null;
	       try {
	           StringBuffer sb = new StringBuffer();
	           if(method==null || method.equals("GET")){
	               strUrl = strUrl+"?"+urlencode(params);
	           }
	           URL url = new URL(strUrl);
	           conn = (HttpURLConnection) url.openConnection();
	           if(method==null || method.equals("GET")){
	               conn.setRequestMethod("GET");
	           }else{
	               conn.setRequestMethod("POST");
	               conn.setDoOutput(true);
	           }
	           conn.setRequestProperty("User-agent", userAgent);
	           conn.setUseCaches(false);
	           conn.setConnectTimeout(DEF_CONN_TIMEOUT);
	           conn.setReadTimeout(DEF_READ_TIMEOUT);
	           conn.setInstanceFollowRedirects(false);
	           conn.connect();
	           if (params!= null && method.equals("POST")) {
	               try {
	                   DataOutputStream out = new DataOutputStream(conn.getOutputStream());
	                       out.writeBytes(urlencode(params));
	               } catch (Exception e) {
	            	   
	               }
	           }
	           InputStream is = conn.getInputStream();
	           reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
	           String strRead = null;
	           while ((strRead = reader.readLine()) != null) {
	               sb.append(strRead);
	           }
	           rs = sb.toString();
	       } catch (IOException e) {
	           e.printStackTrace();
	       } finally {
	           if (reader != null) {
	               reader.close();
	           }
	           if (conn != null) {
	               conn.disconnect();
	           }
	       }
	       return rs;
	   }

	   //将map型转为请求参数型
	   @SuppressWarnings("rawtypes")
	   public static String urlencode(Map<String,Object>data) {
	       StringBuilder sb = new StringBuilder();
	       for (Map.Entry i : data.entrySet()) {
	           try {
	               sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
	           } catch (UnsupportedEncodingException e) {
	               e.printStackTrace();
	           }
	       }
	       return sb.toString();
	   }
	   
	   public void repair(){
		   renderJsp("youbao.jsp");
	   }
	   
	   public void getCode(){
			String code ="-1";
			System.out.println("messageCode--->"+getRequest().getSession().getAttribute("messageCode"));
			if(getRequest().getSession().getAttribute("messageCode") != null){
				String messageCode=getRequest().getSession().getAttribute("messageCode").toString();
				String inputcode=getPara("inputcode");
				System.out.println("inputCode-->"+inputcode);
				if(inputcode.equals(messageCode)){
					String openid = (String) getRequest().getSession().getAttribute("openId");
					Person person = Person.dao.getUserByOpenId(openid);
					String telNum = getPara("telNum");
					if(person == null){
						new Person().set("openid", openid).set("ptel", telNum).set("registerTime",new Date()).save();
					}else{
						person.set("ptel", telNum).update();
					}
					code="0";

				}
			}
			com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
			jo.put("code", code);
			System.out.println("code:"+code);
			renderJson(jo.toString());
		}
	   
//	   //接收前台的发送红包请求，以session中的token作为验证，验证后销毁token,跳转亿程授权
//		public void reds(){
//			if(getRequest().getSession().getAttribute("token") != null){
//				String token = getRequest().getSession().getAttribute("token").toString();
//				if(getPara("token") != null && getPara("token").equals(token)){
//					getRequest().getSession().removeAttribute("token");
////					System.out.println("session 是否被销毁："+getRequest().getSession().getAttribute("token"));
//					redirect(SnsAccessTokenApi.getYCOpenid(PropKit.get("domain")+"person/sendred"));
//					return;
//				}
//			}
//			renderHtml("sorry! you not code……");
//		}
		
	   //接收亿程授权后的回调，通过code获取openid后发送红包，跳转界面。
//		public void sendred(){
//		   String code = getPara("code");
//		   if(code != null){
//			   SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken("wx473eda9a3e0d8207", "2651ffab42eef1acbcd85d07b1e22315",code);
//			   String openId = accessToken.getOpenid();
//			   if(openId != null){
////				   PersonService service = new PersonService();
////				   service.sendRed(openId);
//				   setAttr("red", 1);
//			   }
//		   }
//		   getUserInfo();
//		   //修改数据
//		  // render("userInfo2.jsp");
//		   render("userInfo3.jsp");
////		   redirect("index");
//	   }
		/**
		 * 反馈
		 */
	public void feedback(){
		String content=getPara("content");
		String tel=getPara("tel");
		System.out.println("content=="+content+"--tel=="+ tel+"  time : "+new Date());
		new FeedBack().set("content", content).set("tel",tel).set("time",new Date()).save();
		com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
		jo.put("code", 0);
		renderJson(jo.toString());
	}
	

}
